<template>
<div class="demo-table-wrapper">
  <el-table
    :data="editTbleDatas.editData"
    border
    stripe
    :header-cell-style="{ background: '#DFF1FD', fontWeight: 900 }"
    :row-class-name="tableRowClassName"
    @row-click="rowClickHandle"
    ref="elEditTableRef"
  >
    <el-table-column v-for="(item, index) in editTbleDatas.head" :key="index" :render-header="renderHeader" :label="item.name" :prop="item.value" class="is-required">
      <template #default="scope">
        <!-- <label for="0" class="is-required"></label> -->
        <el-input
          v-if="item.type == 'input' && currRow == scope.$index"
          v-model.trim="scope.row[item.value]"
          @keyup.enter="item.onclick(scope)"
          @dblclick="item.onclick ? item.onclick(scope) : false"
        />
        <el-input
          v-if="item.type == 'numberInput' && currRow == scope.$index"
          v-model.trim="scope.row[item.value]"
          type="number"
          :placeholder="item.placeholder"
          :disabled="item.disabled"
        >
        </el-input>
        <el-switch
          v-if="item.type == 'switch' && currRow == scope.$index"
          v-model.trim="scope.row[item.value]"
          :active-value="item.options.true"
          :inactive-value="item.options.false"
        />
        <el-select v-if="item.type == 'select' && currRow == scope.$index" v-model.trim="scope.row[item.value]" clearable>
          <el-option v-for="(item, index) in item.options" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>

        <el-radio-group v-if="item.type == 'radio'" v-model.trim="scope.row[item.value]" size="small">
          <!-- <el-radio-button label="left" />
            <el-radio-button label="center" />
            <el-radio-button label="right" /> -->
          <el-radio v-for="(obj, index) in item.options" :key="index" :label="obj.value" border>{{ obj.name }}</el-radio>
        </el-radio-group>
      </template>
    </el-table-column>

    <el-table-column label="操作" fixed="right" v-if="!editTbleDatas.hideButton">
      <template #default="scope">
        <el-button type="primary" :icon="Plus" circle @click="insertRow(scope)" />
        <el-button type="danger" :icon="Delete" circle @click="deleteRow(scope)" />
      </template>
    </el-table-column>
  </el-table>
  </div>
</template>
<script setup name="editTbleBody">
import { reactive, ref, h,nextTick } from 'vue'
import { Delete, Plus } from '@element-plus/icons-vue'
import http from '@/components/utils/http'
import { deepClone } from '@/components/utils/api'
import { ElNotification } from 'element-plus'
import Sortable from 'sortablejs'
const props = defineProps({
  editTbleDatas: Object
})
const elEditTableRef = ref()
const editTbleDatas = props.editTbleDatas
const currRow = ref(0)
const addrow = () => {
  editTbleDatas.editData.push(editTbleDatas.getRow())
}
const tableRowClassName = ({ row, rowIndex }) => {
  // 把每一行的索引放进row
  row.index = rowIndex
  if (rowIndex % 2 == 0) {
    return 'warning-row'
  } else {
    return 'warning-rows'
  }
}
const deleteRow = ({ $index }) => {
  editTbleDatas.editData.splice($index, 1)
}
const isCurrRow = index => {
  return true
}
const rowClickHandle = row => {
  currRow.value = row.index
  editTbleDatas.currRow = currRow;
}
const insertRow = ({ $index }) => {
  editTbleDatas.editData.splice($index, 0, editTbleDatas.getRow())
}
const setFoucs = (index, columnValue) => {
  console.log(elEditTableRef.value.getSelectionRows())
}
const tableRules = () => {
  let result = false
  for (const head of editTbleDatas.head) {
    if (head.rule) {
      if (head.rule.required === true) {
        const editData = editTbleDatas.editData
        for (let index = 0; index < editData.length; index++) {
          const currData = editData[index]
          if ((currData[head.value] && currData[head.value] !== '') || currData[head.value] === 0) {
            result = true
          } else {
            currRow.value = index
            // setFoucs(index,head.value)
            ElNotification({ title: 'Error', message: `第${index + 1}行${head.name}不可以为空`, type: 'error' })
            return false
          }
        }
      }
    }
  }
  return result
}
const renderHeader = ({ column }) => {
  const arr = editTbleDatas.head.find(item => item.name === column.label && item.rule && item.rule.required === true)
  if (arr) {
    return [h('span', ' ' + column.label), h('span', { style: 'color: red' }, '*')]
  } else {
    return column.label
  }
}
const moveArrItem = (x,y)=>{
  nextTick(()=>{
    const arr = editTbleDatas.editData;
  let ori = arr[x].head_sort
  arr[x].head_sort = arr[y].head_sort
  arr[y].head_sort = ori
  })
}
const dragRow = ()=> {
        // 查找要拖拽元素的父容器
  const tbody = document.querySelector('.demo-table-wrapper .el-table__body-wrapper tbody')
  console.log(tbody);
  
  Sortable.create(tbody, {
    draggable: '.demo-table-wrapper .el-table__row', //  指定父容器下可被拖拽的子元素

    onEnd(row) {
      const { newIndex, oldIndex } = row;
      /**
        * onEnd 拖拽结束后的事件处理函数
        * newIndex：目标位置对应行的索引
        * oldIndex：被拖拽行的索引
        *
        * ====================（被拖拽记录行1）
        * before
        * ====================(拖拽至目标位置对应记录行)
        * after
        * ====================（被拖拽记录行2）
        * 如果从上往下拖拽，即newIndex > oldIndex，那么在目标位置对应记录行上移(目标位置对应记录行索引值减1)，在newIndex所指位置插入被拖拽行(被拖拽行索引设置为newIndex)，视觉效果就是在after位置(即目标位置对应行下方)插入被拖拽行
        * 如果从下往上拖拽，即newIndex < oldIndex，那么在目标位置对应记录行下移(目标位置对应记录行索引值加1)，在newIndex所指位置插入被拖拽行(被拖拽行索引设置为newIndex)，视觉效果就是在上述before位置(即目标位置对应行上方)插入被拖拽行
        * */
      console.log( oldIndex,newIndex)
      moveArrItem(oldIndex,newIndex);
      if (newIndex > oldIndex) {
        // 请求服务器做数据更新处理，然后根据处理结果对前端页面处理
      } else {
        // 请求服务器做数据更新处理 ，然后根据处理结果对前端页面处理
      }
    },
  })
}
nextTick(()=>{
  // dragRow()
})

defineExpose({ tableRules })
</script>



<style lang="scss" scoped>
.is-required::before {
  content: '*';
  color: var(--el-color-danger);
  margin-right: 4px;
}
.demo-table-wrapper{}
</style>